package com.bookpavilion.search.service;

import com.bookpavilion.search.dao.GoodsDao;
import com.bookpavilion.search.pojo.Goods;
import org.apache.commons.collections.IteratorUtils;

import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;

import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.stereotype.Service;
import util.IdWorker;

import java.util.Iterator;
import java.util.List;

@Service
public class GoodsService {
    @Autowired
    private GoodsDao goodsDao;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    public void  save(Goods goods){
        goods.setId(idWorker.nextId()+"");
        goods.setStatus(1);
        goodsDao.save(goods);
    }

    public List<Goods> findAll(){
        Iterable<Goods> all = goodsDao.findAll();
        Iterator<Goods> iterator = all.iterator();
        List<Goods> goods = IteratorUtils.toList(iterator);
        return goods;
    }

    public Page<Goods> findByKey(String keyword, int page, int size) {
        Pageable pageable = PageRequest.of(page-1,size);
        return goodsDao.findByIntroductionOrGoodsname(keyword,keyword,pageable);
    }

    public void delete(String id) {
        goodsDao.deleteById(id);
    }

    public Page<Goods> findByCategoryId(String categoryId,int page,int size) {
        TermQueryBuilder termQuery = QueryBuilders.termQuery("category_id", categoryId);
        Pageable pageable = PageRequest.of(page-1,size);
        Page<Goods> pages = goodsDao.search(termQuery,pageable);
        return pages;
    }
}
